<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header :addTodo="addTodo" />
      <List :todos="todos" :deleteTodo="deleteTodo" :updateTodo="updateTodo" />
      <Footer
        :todos="todos"
        :checkAll="checkAll"
        :clearAllComplateTodos="clearAllComplateTodos"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, watch } from "vue";
import Header from "@/components/Todolist/Header.vue";
import List from "@/components/Todolist/List.vue";
import Footer from "@/components/Todolist/Footer.vue";
import { Todo } from "@/types/todo";
import { saveTodos, readTodos } from "@/utils/useAppData";
export default defineComponent({
  name: "Todolist",
  components: {
    Header,
    List,
    Footer,
  },
  setup() {
    const state = reactive<{ todos: Todo[] }>({
      todos: [],
    });
    onMounted(() => {
      setTimeout(() => {
        state.todos = readTodos();
      }, 0);
    });
    const addTodo = (todo: Todo) => {
      state.todos.unshift(todo);
    };
    const deleteTodo = (index: number) => {
      state.todos.splice(index, 1);
    };
    const updateTodo = (todo: Todo, isCompleted: boolean) => {
      todo.isCompleted = isCompleted;
    };
    const checkAll = (isCompleted: boolean) => {
      state.todos.forEach((todo) => (todo.isCompleted = isCompleted));
    };
    const clearAllComplateTodos = () => {
      state.todos = state.todos.filter((todo) => !todo.isCompleted);
    };
    watch(() => state.todos, saveTodos, { deep: true });

    return {
      ...toRefs(state),
      addTodo,
      deleteTodo,
      updateTodo,
      checkAll,
      clearAllComplateTodos,
    };
  },
});
</script>

<style lang="scss" scoped>
.todo-container {
  width: 600px;
  margin: 0 auto;
  .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
}
</style>
